/*import i18n from '@root/i18n';

// 由于服务端中用户群体广泛，来源多样，建议在每个 t 函数中显式传入当前用户的语言标识，以确保多语言内容能够正确匹配用户所需的语言版本。
console.log('(server)：', i18n.t('welcome_game', { lng: 'zh-CN' }));
console.log('(server)：', i18n.t('welcome_ap', { lng: 'en' }));
*/

world.addCollisionFilter('player', 'player');
world.addCollisionFilter('*', '*');

// 立方体建造函数（优化版）
function buildCube(startX, startY, startZ, sizeX, sizeY, sizeZ, blockType = "stone") {
    const endX = startX + sizeX;
    const endY = startY + sizeY;
    const endZ = startZ + sizeZ;
    
    for(let x = startX; x < endX; x++) {
        for(let y = startY; y < endY; y++) {
            for(let z = startZ; z < endZ; z++) {
                voxels.setVoxel(x, y, z, blockType);
            }
        }
    }
    console.log(`建造实心立方体完成 (${sizeX}x${sizeY}x${sizeZ})`);
}

// 分队系统：红队保护南瓜，蓝队毁灭南瓜
const Defaultscale = [0.625, 0.625, 0.625];

// 队伍定义
const TEAMS = {
    RED: 'red',    // 红队：保护南瓜
    BLUE: 'blue'   // 蓝队：毁灭南瓜
};

// 游戏状态
let gameState = {
    inGame: false,
    startTime: 0,
    pumpkinCount: 0,
    teams: {
        [TEAMS.RED]: [],
        [TEAMS.BLUE]: []
    },
    maxGameTime: 15 * 60 * 1000, // 15分钟
    gameArea: {
        minX: 0,
        maxX: 256,
        minZ: 0,
        maxZ: 256,
        centerY: 55
    }
};

//GUI初始化 - 增强版菜单系统
world.onPlayerJoin(({ entity }) => {
    entity.player.enable3DCursor = true;
    entity.team = null;
    entity.cameraMode = GameCameraMode.FOLLOW; // 默认跟随视角
    entity.skillCold = 0;
    entity.skill = '加速(默认)';

    gui.init(entity, {
        "panel": {
            display: true,
            data: `<dialog width="400" percentHeight="100" top="60" right="60" id="mainPanel">
            <group percentWidth="100" height="150" y="0">
                <label text="南瓜保卫战" height="40" y="5" x="10" percentWidth="100" color="#FF6B35" fontSize="22" fontWeight="bold"></label>
                <label text="" height="30" y="45" x="10" percentWidth="100" color="#FF4444" id="teamInfo" fontSize="16"></label>
                <label text="" height="30" y="75" x="10" percentWidth="100" color="#44FF44" id="taskInfo" fontSize="14"></label>
                <label text="" height="30" y="105" x="10" percentWidth="100" color="#4444FF" id="pumpkinCount" fontSize="14"></label>
            </group>
            <group percentWidth="100" height="120" y="160">
                <label text="游戏信息" height="35" y="5" x="10" percentWidth="100" color="#FF6B35" fontSize="18"></label>
                <label text="" height="25" y="40" x="10" percentWidth="100" color="#FFAA00" id="gameTime"></label>
                <label text="" height="25" y="65" x="10" percentWidth="100" color="#FFAA00" id="redTeam"></label>
                <label text="" height="25" y="90" x="10" percentWidth="100" color="#FFAA00" id="blueTeam"></label>
            </group>
            <group percentWidth="100" height="100" y="290">
                <label text="控制面板" height="35" y="5" x="10" percentWidth="100" color="#FF6B35" fontSize="18"></label>
                <label text="右键: 打开菜单 | 左键: 队伍技能" height="25" y="40" x="10" percentWidth="100" color="#AAAAAA" fontSize="12"></label>
                <label text="技能冷却显示在下方" height="25" y="65" x="10" percentWidth="100" color="#AAAAAA" fontSize="12"></label>
            </group>
            <group percentWidth="100" height="100" y="400">
                <label text="技能信息" height="35" y="5" x="10" percentWidth="100" color="#FF6B35" fontSize="18"></label>
                <label text="" height="30" y="40" x="10" percentWidth="100" color="#a0a" id="skillName" fontSize="16"></label>
                <label text="" height="30" y="70" x="10" percentWidth="100" color="#a0a" id="skillStatus" fontSize="14"></label>
            </group>
        </dialog>`
        }
    });

    // 更新GUI信息
    world.onTick(() => {
        updatePlayerGUI(entity);

        // 更新技能冷却显示
        var space = (entity.skillCold / 1000);
        var isdown = space <= 0;
        var Ystatus = (isdown ? "可用" : "还剩" + space.toFixed(1) + '秒冷却');

        gui.setAttribute(entity, "#skillName", "text", `技能名称: ${entity.skill}`);
        gui.setAttribute(entity, "#skillStatus", "text", `技能状态: ${Ystatus}`);
    });
});

// 更新玩家GUI信息
function updatePlayerGUI(entity) {
    if (gameState.inGame) {
        const elapsedTime = Date.now() - gameState.startTime;
        const remainingTime = Math.max(0, gameState.maxGameTime - elapsedTime);
        const minutes = Math.floor(remainingTime / 60000);
        const seconds = Math.floor((remainingTime % 60000) / 1000);

        const teamName = entity.team ? (entity.team === TEAMS.RED ? '红队' : '蓝队') : '未加入';
        const taskDesc = entity.team ? (entity.team === TEAMS.RED ? '任务: 保护南瓜，清除熔岩' : '任务: 毁灭南瓜，放置熔岩') : '请右键打开菜单查看信息';

        gui.setAttribute(entity, "#teamInfo", "text", `队伍: ${teamName}`);
        gui.setAttribute(entity, "#taskInfo", "text", taskDesc);
        gui.setAttribute(entity, "#pumpkinCount", "text", `南瓜数量: ${gameState.pumpkinCount}`);
        gui.setAttribute(entity, "#gameTime", "text", `剩余时间: ${minutes}:${seconds.toString().padStart(2, '0')}`);
        gui.setAttribute(entity, "#redTeam", "text", `红队: ${gameState.teams[TEAMS.RED].length}人`);
        gui.setAttribute(entity, "#blueTeam", "text", `蓝队: ${gameState.teams[TEAMS.BLUE].length}人`);
    } else {
        gui.setAttribute(entity, "#teamInfo", "text", "队伍: 等待分配");
        gui.setAttribute(entity, "#taskInfo", "text", "游戏开始后自动分配队伍");
        gui.setAttribute(entity, "#pumpkinCount", "text", "南瓜数量: 0");
        gui.setAttribute(entity, "#gameTime", "text", "剩余时间: 15:00");
        gui.setAttribute(entity, "#redTeam", "text", `红队: ${gameState.teams[TEAMS.RED].length}人`);
        gui.setAttribute(entity, "#blueTeam", "text", `蓝队: ${gameState.teams[TEAMS.BLUE].length}人`);
    }
}

// 生成南瓜实体 - 扩展至256x256范围
function spawnPumpkin(x, y, z) {
    const entity = world.createEntity({
        mesh: 'mesh/25万创 最后一盏南瓜灯.vb',
        scale: Defaultscale,
        position: [x, y, z],
        collides: true,
        gravity: true,
        fixed: false,
        friction: 0.8,
    });

    entity.addTag('pumpkin');
    entity.enableDamage = true;
    gameState.pumpkinCount++;

    // 南瓜被接触时的行为
    entity.onVoxelContact(({ x, y, z, voxel }) => {
        entity.velocity.x = (Math.random() - 0.5) * 0.5;
        entity.velocity.y = 0.5 + (Math.random()) * 0.5;
        entity.velocity.z = (Math.random() - 0.5) * 0.5;

        if (voxel === voxels.id('stone')) {
            // 石头不处理
        } else if (voxel === voxels.id('lava02')) {
            entity.hurt(20); // 被熔岩灼烧
        } else {
            // 其他方块被破坏
            voxels.setVoxel(x, y, z, '');
        }
    });

    // 南瓜死亡处理
    entity.onDie(() => {
        gameState.pumpkinCount--;
        entity.destroy();
        world.say(`南瓜被毁灭！剩余数量: ${gameState.pumpkinCount}`);

        // 检查游戏是否结束
        checkGameEnd();
    });

    return entity;
}

// 优化随机分队系统 - 当有一人在红队时另一人分配到蓝队
async function assignRandomTeams() {
    // 清除旧队伍
    gameState.teams[TEAMS.RED] = [];
    gameState.teams[TEAMS.BLUE] = [];

    // 获取所有玩家
    const players = world.querySelectorAll('player');
    
    // 如果只有1名玩家，直接分配到红队
    if (players.length === 1) {
        const entity = players[0];
        entity.team = TEAMS.RED;
        gameState.teams[TEAMS.RED].push(entity.player.name);
        entity.player.directMessage('你被分配到红队（保护南瓜）！');
        world.say(`分队完成！红队: 1人，蓝队: 0人`);
        return;
    }
    
    // 如果有2名玩家，一人红队一人蓝队
    if (players.length === 2) {
        players[0].team = TEAMS.RED;
        players[1].team = TEAMS.BLUE;
        gameState.teams[TEAMS.RED].push(players[0].player.name);
        gameState.teams[TEAMS.BLUE].push(players[1].player.name);
        
        players[0].player.directMessage('你被分配到红队（保护南瓜）！');
        players[1].player.directMessage('你被分配到蓝队（毁灭南瓜）！');
        world.say(`分队完成！红队: 1人，蓝队: 1人`);
        return;
    }

    // 3名以上玩家，随机分配但保持平衡
    const shuffledPlayers = [...players].sort(() => Math.random() - 0.5);
    const half = Math.ceil(shuffledPlayers.length / 2);
    
    for (let i = 0; i < shuffledPlayers.length; i++) {
        const entity = shuffledPlayers[i];
        const team = i < half ? TEAMS.RED : TEAMS.BLUE;

        entity.team = team;
        gameState.teams[team].push(entity.player.name);

        // 设置队伍特定能力
        if (team === TEAMS.RED) {
            entity.player.directMessage('你被分配到红队（保护南瓜）！你可以破坏方块和清除熔岩。控制说明：左键清除熔岩，右键打开菜单');
        } else {
            entity.player.directMessage('你被分配到蓝队（毁灭南瓜）！你可以在身后放置熔岩方块。控制说明：走动时自动放置熔岩，右键打开菜单');
        }
    }

    world.say(`分队完成！红队: ${gameState.teams[TEAMS.RED].length}人，蓝队: ${gameState.teams[TEAMS.BLUE].length}人`);
}

// 玩家接触方块的处理（根据队伍设置不同权限）
world.onVoxelContact(({ x, y, z, voxel, entity }) => {
    if (!entity.isPlayer || !gameState.inGame) return;

    const voxelName = voxels.name(voxel);

    if (entity.team === TEAMS.BLUE) {
        // 蓝队不能破坏方块（除了特殊处理）
        return;
    }

    // 红队可以破坏方块（除了石头和基岩），特别是熔岩
    if ((voxelName !== 'stone' && voxelName !== 'bedrock') || voxelName === 'lava02') {
        voxels.setVoxel(x, y, z, '');
        if (voxelName === 'lava02') {
            entity.player.directMessage('熔岩已被清除！');
        }
    }
});

// 蓝队走动时在身后放置熔岩方块
world.onVoxelContact(({ x, y, z, voxel, entity }) => {
    if (!entity.isPlayer || !gameState.inGame || entity.team !== TEAMS.BLUE) return;
    
    // 蓝队玩家接触方块时，在接触位置上方放置熔岩
    voxels.setVoxel(x, y+1, z, 'lava02');
});

// 技能列表
var skillList = [
    {
        name: '加速(默认)',
        introduce: `持续5秒的加速`,
        notice: '最好别用这个技能',
        cold: 15000,
        async effect(entity, raycast) {
            entity.player.runSpeed += 0.4;
            entity.player.walkSpeed = entity.player.runSpeed;
            Object.assign(entity, {
                particleRate: 999,
                particleColor: new GameRGBColor(1, 1, 1),
                particleLifetime: 0.3,
                particleSize: [5, 4, 3, 2, 2]
            });
            await sleep(5000);
            if (entity.player.runSpeed > 0.4) {
                entity.player.runSpeed -= 0.4;
                entity.player.walkSpeed = entity.player.runSpeed;
            }
            entity.player.directMessage('加速效果结束');
            Object.assign(entity, {
                particleRate: 0,
            });
        }
    },
    {
        name: '恢复',
        introduce: `恢复70%最大血量`,
        notice: '真有用啊！',
        cold: 40000,
        async effect(entity, raycast) {
            entity.hp += 70;
            if (entity.hp > entity.maxHp) {
                entity.hp = entity.maxHp;
            }
        }
    },
    {
        name: '冲刺',
        introduce: `向准星瞄准的方向冲刺，击打到玩家时可以击退目标`,
        notice: '小心冲刺过猛！',
        cold: 60000,
        async effect(entity, raycast) {
            if (raycast) {
                var k = raycast.hitPosition;
                var direction = k.sub(entity.position);
                var dist = direction.mag();
                var speed = 2;
                if (raycast.hitEntity && raycast.hitEntity.isPlayer) {
                    raycast.hitEntity.velocity.x = direction.x * speed / dist;
                    raycast.hitEntity.velocity.z = direction.z * speed / dist;
                    raycast.hitEntity.velocity.y += 1;
                    raycast.hitEntity.player.directMessage('你被' + entity.player.name + '的技能【冲刺】击中了');
                }
                entity.velocity.x = direction.x * speed / dist;
                entity.velocity.z = direction.z * speed / dist;
                entity.velocity.y = 0;
            }
        }
    }
];

// 获取技能信息
function getSkill(name) {
    var object = Object.values(skillList).find(e => e.name == name);
    if (object) {
        return object;
    } else {
        return null;
    }
}

// 按键控制：右键打开菜单
world.onPress(async ({ button, entity, raycast }) => {
    if (!entity.isPlayer) return;

    // 右键：打开菜单
    if (button === 'action1') {
        await showMainMenu(entity, raycast);
    }

    // 左键：队伍特定技能
    if (button === 'action0' && gameState.inGame) {
        if (entity.skillCold > 0) return;

        var skill = await getSkill(entity.skill);
        if (skill) {
            entity.skillCold = skill.cold;
            skill.effect(entity, raycast);
            entity.player.directMessage('你使用了技能' + entity.skill);
        }
    }
});

// 显示主菜单
async function showMainMenu(entity, raycast) {
    if (gameState.inGame) {
        // 游戏进行中，显示游戏菜单
        const choice = await entity.player.dialog({
            type: 'select',
            title: '游戏菜单',
            content: `当前队伍: ${entity.team ? (entity.team === TEAMS.RED ? '红队' : '蓝队') : '未分配'}\n游戏时间: ${formatTime(Date.now() - gameState.startTime)}\n南瓜数量: ${gameState.pumpkinCount}`,
            options: ['游戏状态', '切换技能', '游戏规则', '关闭菜单','重生']
        });

        if (choice) {
            switch (choice.index) {
                case 0: // 游戏状态
                    await showGameStatus(entity);
                    await showMainMenu(entity, raycast);
                    break;
                case 1: // 切换技能
                    await showSkillMenu(entity);
                    await showMainMenu(entity, raycast);
                    break;
                case 2: // 游戏规则
                    await showGameRules(entity);
                    await showMainMenu(entity, raycast);
                    break;
                case 3: // 关闭菜单
                    break;
                case 4: // 重生
                    entity.player.forceRespawn();
                    break;
            }
        }
    } else {
        // 游戏等待中，显示信息选项
        const choice = await entity.player.dialog({
            type: 'select',
            title: '南瓜保卫战',
            content: '游戏开始后将自动分配队伍\n当前状态: 等待开始',
            options: ['查看游戏规则', '查看技能列表', '关闭菜单','重生']
        });

        if (choice) {
            switch (choice.index) {
                case 0: // 查看规则
                    await showGameRules(entity);
                    await showMainMenu(entity, raycast);
                    break;
                case 1: // 查看技能
                    await showSkillMenu(entity);
                    await showMainMenu(entity, raycast);
                    break;
                case 2: // 关闭菜单
                    break;
                case 3: // 重生
                    entity.player.forceRespawn();
                    break;
            }
        }
    }
}

// 显示游戏状态
async function showGameStatus(entity) {
    await entity.player.dialog({
        type: 'text',
        title: '游戏状态',
        content: `当前队伍: ${entity.team ? (entity.team === TEAMS.RED ? '红队' : '蓝队') : '未分配'}\n\n` +
            `游戏时间: ${formatTime(Date.now() - gameState.startTime)}\n` +
            `南瓜数量: ${gameState.pumpkinCount}\n` +
            `红队人数: ${gameState.teams[TEAMS.RED].length}\n` +
            `蓝队人数: ${gameState.teams[TEAMS.BLUE].length}\n\n` +
            `${entity.team === TEAMS.RED ?
                '你的任务: 保护南瓜，清除熔岩方块' :
                '你的任务: 毁灭南瓜，放置熔岩方块'}`
    });
}

// 显示技能菜单
async function showSkillMenu(entity) {
    var list = [];
    for (let i = 0; i < skillList.length; i++) {
        list.push(skillList[i].name);
    }

    const select = await entity.player.dialog({
        type: 'select',
        title: '切换技能',
        content: '当前技能: ' + entity.skill,
        options: list
    });

    if (select) {
        var skill = await getSkill(select.value);
        const sel = await entity.player.dialog({
            type: 'select',
            title: select.value,
            content: skill.introduce + `\n` + 'CD:' + (skill.cold / 1000) + '秒' + `\n` + `注意事项:` + skill.notice,
            options: ['切换到此技能', '返回']
        });

        if (sel && sel.index === 0) {
            entity.skill = select.value;
            entity.player.directMessage('切换技能至' + select.value);
        }
    }
}

// 显示游戏规则
async function showGameRules(entity) {
    await entity.player.dialog({
        type: 'text',
        title: '游戏规则',
        content: `南瓜保卫战规则说明：\n\n` +
            `红队目标：\n- 保护南瓜存活15分钟\n- 清除蓝队放置的熔岩\n- 左键使用清除技能\n\n` +
            `蓝队目标：\n- 在15分钟内毁灭所有南瓜\n- 走动时自动放置熔岩\n- 左键使用加速放置技能\n\n` +
            `控制说明：\n- 右键: 打开菜单\n- 左键: 使用队伍技能\n\n` +
            `游戏时间：15分钟\n` +
            `地图范围：256x256\n\n` +
            `注意：队伍自动分配，无法手动选择`
    });
}

// 实体接触处理（南瓜对玩家的伤害）
world.onEntityContact(({ other, entity }) => {
    if (gameState.inGame && other.isPlayer && entity.hasTag('pumpkin')) {
        other.hurt(5);
        other.player.directMessage('你被南瓜撞到了！');
    }
});

// 玩家死亡处理
world.onDie(({ entity, damageType }) => {
    if (entity.isPlayer) {
        world.say(`${entity.player.name} ${damageType}，阵亡了！`);

        // 5秒后复活
        setTimeout(() => {
            if (gameState.inGame) {
                entity.player.forceRespawn();
                // 复活在安全区域（256x256范围内）
                entity.position.set(
                    Math.random() * 256,
                    gameState.gameArea.centerY + 2,
                    Math.random() * 256
                );
            }
        }, 5000);
    }
});

// 恢复游戏场地
async function restoreGameArea() {
    world.say('正在恢复游戏场地...');
    
    // 建造泥土层作为地面 (0-17层)
    buildCube(0, 1, 0, 256, 17, 256, 'dirt');
    
    // 清除上方的空气层 (18-57层)
    buildCube(0, 18, 0, 256, 40, 256, 'air');
    
    world.say('游戏场地恢复完成！');
}

// 检查游戏是否结束
function checkGameEnd() {
    if (!gameState.inGame) return;

    const elapsedTime = Date.now() - gameState.startTime;

    // 蓝队胜利条件：南瓜数量为0
    if (gameState.pumpkinCount <= 0) {
        endGame(TEAMS.BLUE, '蓝队成功毁灭了所有南瓜！');
        return;
    }

    // 红队胜利条件：坚持15分钟
    if (elapsedTime >= gameState.maxGameTime) {
        endGame(TEAMS.RED, '红队成功保护南瓜15分钟！');
        return;
    }
}

// 结束游戏
async function endGame(winningTeam, message) {
    gameState.inGame = false;

    world.say(`游戏结束！${message}`);
    world.say(`${winningTeam === TEAMS.RED ? '红队' : '蓝队'}获胜！`);

    // 清理所有南瓜
    world.querySelectorAll('.pumpkin').forEach(pumpkin => {
        pumpkin.destroy();
    });

    // 恢复游戏场地
    await restoreGameArea();

    // 重置玩家状态
    world.querySelectorAll('player').forEach(player => {
        player.enableDamage = false;
        player.player.forceRespawn();
        player.team = null;
        player.skillCold = 0;
    });

    // 5秒后开始新游戏
    setTimeout(startGame, 5000);
}

// 开始游戏
async function startGame() {
    if (gameState.inGame) return;

    // 随机分队
    await assignRandomTeams();

    // 检查队伍平衡
    if (gameState.teams[TEAMS.RED].length === 0 || gameState.teams[TEAMS.BLUE].length === 0) {
        world.say('需要红蓝两队都有玩家才能开始游戏！');
        return;
    }

    world.say('南瓜保卫战开始！');
    world.say('红队保护南瓜，蓝队毁灭南瓜！');
    world.say('游戏将在15分钟后结束，或当所有南瓜被毁灭时结束！');
    world.say('地图范围：256x256');

    gameState.inGame = true;
    gameState.startTime = Date.now();
    gameState.pumpkinCount = 0;

    // 生成南瓜（在256x256范围内）
    for (let i = 0; i < 50; i++) {
        spawnPumpkin(
            Math.random() * 256,
            gameState.gameArea.centerY,
            Math.random() * 256
        );
    }

    // 设置玩家初始位置和状态
    world.querySelectorAll('player').forEach(player => {
        if (gameState.teams[TEAMS.RED].includes(player.player.name) ||
            gameState.teams[TEAMS.BLUE].includes(player.player.name)) {
            player.enableDamage = true;
            player.maxHp = 100;
            player.hp = player.maxHp;
            player.position.set(
                Math.random() * 256,
                gameState.gameArea.centerY + 2,
                Math.random() * 256
            );
        }
    });
}

// 玩家离开游戏处理
world.onPlayerLeave(({ entity }) => {
    if (entity.team && gameState.teams[entity.team].includes(entity.player.name)) {
        const index = gameState.teams[entity.team].indexOf(entity.player.name);
        if (index > -1) {
            gameState.teams[entity.team].splice(index, 1);
        }
        world.say(`${entity.player.name} 离开了！`);

        // 检查游戏是否应该提前结束
        if (gameState.inGame) {
            const redCount = gameState.teams[TEAMS.RED].length;
            const blueCount = gameState.teams[TEAMS.BLUE].length;
            
            if (redCount === 0 || blueCount === 0) {
                const winner = redCount === 0 ? TEAMS.BLUE : TEAMS.RED;
                endGame(winner, `由于${winner === TEAMS.BLUE ? '红队' : '蓝队'}无人，游戏提前结束！`);
            }
        }
    }
});

// 格式化时间显示
function formatTime(milliseconds) {
    const minutes = Math.floor(milliseconds / 60000);
    const seconds = Math.floor((milliseconds % 60000) / 1000);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

// 游戏主循环
async function gameLoop() {
    while (true) {
        // 等待足够玩家加入
        while (world.querySelectorAll('player').length < 2) {
            world.say('等待更多玩家加入...至少需要2名玩家才能开始游戏！');
            await sleep(10000);
        }
        
        world.say('游戏将在10秒后开始！');
        await sleep(10000);
        
        await startGame();
        
        // 等待游戏结束
        while (gameState.inGame) {
            await sleep(1000);
            
            // 更新技能冷却
            world.querySelectorAll('player').forEach(player => {
                if (player.isPlayer) {
                    player.skillCold -= 1000;
                    if (player.skillCold < 0) {
                        player.skillCold = 0;
                    }
                }
            });
            
            // 定期检查游戏结束条件
            checkGameEnd();
        }
        
        await sleep(5000); // 游戏结束等待时间
    }
}

// 辅助函数：睡眠
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// 初始化游戏
gameLoop();

console.log('南瓜保卫战分队系统已加载！');